import java.util.Arrays;

/**
 * @Author YuanYuan
 * @Date 2022/7/16
 * @Time 15:20
 */
public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue(int[] elem,int usedSize) {
        this.elem = elem;
        this.usedSize = usedSize;
    }

    /**
     * 建堆的时间复杂度：O(n)
     *
     * @param array
     */
    public void createHeap(int[] array) {
        elem = Arrays.copyOf(array,usedSize);
        for (int i = (usedSize-1-1)/2; i >=0 ; i--) {
            shiftDown(i,usedSize);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int parent = root;
        //左孩子
        int child = parent*2+1;
        while(child<len) {
            //右孩子大于左孩子
            if(child+1<len&&elem[child]<elem[child+1]) {
                child++;
            }
            if(elem[parent] < elem[child]) {
                swap(elem,parent,child);
            }
            parent = child;
            child = child*2+1;
        }

    }
    private void swap(int[]arr,int ret1,int ret2) {
        int temp = arr[ret1];
        arr[ret1] = arr[ret2];
        arr[ret2] = temp;
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
       if(isFull()) {
           elem = Arrays.copyOf(elem,elem.length*2);
       }
       usedSize++;
       elem[usedSize-1] = val;
       shiftUp(usedSize-1);

    }

    private void shiftUp(int child) {
        int parent = (child-1)/2;
        if(elem[usedSize-1]>elem[0]) {
            swap(elem,usedSize-1,0);
        }
        while(parent>0) {
            if(elem[child] > parent) {
                swap(elem,child,parent);
                child = parent;
                parent = (child-1)/2;
            }
        }

    }

    public boolean isFull() {
        return usedSize==elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        if(isEmpty()) {
            return;
        }
        elem[0] = elem[--usedSize];
        shiftDown(0,usedSize);

    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(isEmpty()) {
            return -1;
        }
        return elem[0];
    }
}
